import Vue from 'vue'
import Router from 'vue-router'

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('../components/Login.vue')
    },
    {
      path: '/home',
      name: 'Home',
      redirect: '/welcome',
      component: () => import('../components/Home.vue'),
      children: [
        {
          path: '/welcome',
          name: 'Welcome',
          component: () => import('../components/Welcome.vue')
        },
        {
          path: '/users',
          name: 'Users',
          component: () => import('../components/user/Users.vue')
        },
        {
          path: '/rights',
          name: 'Rights',
          component: () => import('../components/power/Rights.vue')
        },
        {
          path: '/roles',
          name: 'Roles',
          component: () => import('../components/power/Roles.vue')
        },
        {
          path: '/categories',
          name: 'Cate',
          component: () => import('../components/good/Cate.vue')
        },
        {
          path: '/params',
          name: 'Params',
          component: () => import('../components/good/Params.vue')
        },
        {
          path: '/goods',
          name: 'list',
          component: () => import('../components/good/List.vue')
        },
        {
          path: '/goods/add',
          name: 'goodsAdd',
          component: () => import('../components/good/Add.vue')
        },
        {
          path: '/orders',
          name: 'Order',
          component: () => import('../components/order/Order.vue')
        },
        {
          path: '/reports',
          name: 'Report',
          component: () => import('../components/report/Report.vue')
        }
      ]
    }
  ]
})

// 挂载路由导航守卫
router.beforeEach((to,from,next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来的
  // next 是一个函数，表示放行
  // next() 放行  next('/login) 强制跳转到登录页
  // 如果用户访问的是登录页，直接放行
  if (to.path === '/login') return next()
  // 从sessionStorage中获取保存的token值
  const tokenStr = window.sessionStorage.getItem('token')
   // 如果token的值不存在，强制跳转到登录页
  if (!tokenStr) return next('/login')
  // 存在token，那么就放行
  next()
})



export default router